<html>
  <head>
    <script src="https://apprtc.appspot.com/_ah/channel/jsapi"></script>
  </head>
  <!--
  Helper HTML that redirects Google AppEngine's Channel API to a JS object named
  |androidMessageHandler|, which is expected to be injected into the WebView
  rendering this page by an Android app's class such as AppRTCClient
  -->
  <body onbeforeunload="closeSocket()" onload="openSocket()">
    <script type="text/javascript">
      // QueryString is copy/pasta from
      // chromium's chrome/test/data/media/html/utils.js.
      var QueryString = function () {
        // Allows access to query parameters on the URL; e.g., given a URL like:
        //    http://<url>/my.html?test=123&bob=123
        // parameters can now be accessed via QueryString.test or QueryString.bob.
        var params = {};

        // RegEx to split out values by &.
        var r = /([^&=]+)=?([^&]*)/g;

        // Lambda function for decoding extracted match values. Replaces '+' with
        // space so decodeURIComponent functions properly.
        function d(s) { return decodeURIComponent(s.replace(/\+/g, ' ')); }

        var match;
        while (match = r.exec(window.location.search.substring(1)))
          params[d(match[1])] = d(match[2]);

        return params;
      } ();

      var channel = null;
      var socket = null;

      function openSocket() {
        if (!QueryString.token || !QueryString.token.match(/^[A-z0-9_-]+$/))
          throw "Missing/malformed token parameter: " + QueryString.token;
        channel = new goog.appengine.Channel(QueryString.token);
        socket = channel.open({
          'onopen': function() { androidMessageHandler.onOpen(); },
          'onmessage': function(msg) { androidMessageHandler.onMessage(msg.data); },
          'onclose': function() { androidMessageHandler.onClose(); },
          'onerror': function(err) { androidMessageHandler.onError(err.code, err.description); }
        });
      }

      function closeSocket() {
        socket.close();
      }
    </script>
  </body>
</html>
